package com.cisetech.util;



import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;


/**
 * json工具类
 * @author zhaopeng
 * @date Apr 21, 2015
 */
public class JsonUtils {

	/**
	 * 
	 * @param jsonclass
	 * @param json
	 * @return
	 */
	public static Object json2Obj(Class<Object> jsonclass, String json) {

		Object obj = null;
		GsonBuilder gsonBuilder = new GsonBuilder();

		Gson gson = gsonBuilder.create();
		try {
			obj = gson.fromJson(json, jsonclass);

		} catch (JsonParseException e) {

			e.printStackTrace();
			obj = ParserJSONManual(jsonclass, json);
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return obj;

	}

	/**
	 * 
	 * @throws JSONException
	 * */
	private static Object ParserJSONManual(Class<Object> jsonclass, String s) {

		return null;
	}

	/**
	 * 
	 * @param obj
	 * @return
	 * @throws JSONException
	 */
	public static String obj2Json(Object obj) throws Exception {

		String json = null;
		GsonBuilder gsonb = new GsonBuilder();
		Gson gson = gsonb.create();// 

		try {
			json = gson.toJson(obj);

		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}

	/**
	 * @param obj
	 * @return
	 * @throws JSONException
	 */
	public static String obj2JsonReplaceSpeciaCharacters(Object obj)
			throws Exception {

		String json = null;
		GsonBuilder gsonb = new GsonBuilder();

		Gson gson = gsonb.create();

		try {
			json = gson.toJson(obj);

		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}
}
